import { NextRequest, NextResponse } from 'next/server';
import { PrismaService } from '@/services/database/PrismaService';
import { EntityClusteringService } from '@/services/analysis/EntityClusteringService';
import { PatternRecognitionService } from '@/services/analysis/PatternRecognitionService';

const prismaService = new PrismaService();
const entityService = new EntityClusteringService(prismaService);
const patternService = new PatternRecognitionService(prismaService);

export async function GET(
  request: NextRequest,
  { params }: { params: { address: string } }
) {
  try {
    const { searchParams } = new URL(request.url);
    const chain = searchParams.get('chain');
    const { address } = params;

    if (!chain) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Missing chain parameter',
          timestamp: new Date().toISOString()
        },
        { status: 400 }
      );
    }

    // Get address profile
    const profile = await prismaService.getAddressProfile(address, chain as any);
    
    // Get entity information
    const entity = await entityService.analyzeAddressCluster(address, chain as any);
    
    // Get transaction patterns
    const patterns = await patternService.analyzeTransactionPatterns(address, chain as any);
    
    // Get behavior insights
    const insights = await prismaService.getBehaviorInsights(address);
    
    // Get anomaly alerts
    const alerts = await prismaService.getAnomalyAlerts(address, chain as any, 'active');

    return NextResponse.json({
      success: true,
      data: {
        profile: profile || {
          address,
          chain,
          entityId: entity?.id,
          riskScore: entity?.riskScore || 0,
          totalTransactions: 0,
          totalVolumeUsd: 0,
          firstSeen: new Date(),
          lastActive: new Date(),
          activityScore: 0,
          metadata: {}
        },
        entity,
        patterns,
        insights,
        alerts
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('Failed to analyze address:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to analyze address',
        timestamp: new Date().toISOString()
      },
      { status: 500 }
    );
  }
} 